package liurong.driver.lru;

import java.util.LinkedHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * LRU的实现：继承LinkedHashMap重新实现removeEldestEntry就能实现LRU缓存Map
 * 
 * @author liurong
 *
 * @date 2019年1月26日
 */
public class ConccurentLRUCache<K, V> extends LinkedHashMap<K, V> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static int DEFAULT_CAPACITY = 1000;

	private int capacity = DEFAULT_CAPACITY;

	private Lock lock = new ReentrantLock();

	public ConccurentLRUCache() {
		super();
	}

	public ConccurentLRUCache(int capacity) {
		super();
		this.capacity = capacity;
	}

	@Override
	protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
		return size() > capacity;
	}

	public V put(K key, V value) {
		V put = null;
		try {
			lock.lock();
			put = super.put(key, value);
		} finally {
			lock.unlock();
		}
		return put;
	}

}
